<template>
  <div class="gems-dropdown">
    <Tooltip 
      :trigger="trigger"
      :placement="placement"
      :popper-options="popperOptions"
      :manual="manual"
      :close-delay="closeDelay"
      :open-delay="openDelay"
      @visible-change="visibleChange"
      ref="tooltipRef"
    >
      <slot />
      <template #content>
        <ul class="gems-dropdown__menu">
          <template v-for="item in menuOptions" :key="item.key">
            <li v-if="item.divided" role="separator" class="divided-placeholder"></li>
            <li 
              class="gems-dropdown__item"  
              :class="{ 'is-disabled': item.disabled, 'is-divided': item.divided }"  :id="`dropdown-item-${item.key}`"
              @click="itemClick(item)"
            >
              <RenderVnode :vnode="item.label" />
            </li>
          </template>
        </ul>
      </template>
    </Tooltip>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import type { DropdownProps, DropdownEmits, DropdownInstance, MenuOption } from './types';
import Tooltip from '../Tooltip/Tooltip.vue';
import type { TooltipInstance } from '../Tooltip/types'
import RenderVnode from '../Common/RenderVnode'
defineOptions({
  name: 'GemsDropdown',
})
const props = withDefaults(defineProps<DropdownProps>(), {
  hideAfterClick: true,
})
const emits = defineEmits<DropdownEmits>()
const tooltipRef = ref<TooltipInstance | null>(null)
const visibleChange = (visible: boolean) => {
  emits('visible-change', visible)
}
const itemClick = (item: MenuOption) => {
  if (item.disabled) return
  emits('item-click', item)
  if (props.hideAfterClick) {
    tooltipRef.value?.hide()
  }
}


defineExpose({
  show: () => tooltipRef.value?.show(),
  hide: () => tooltipRef.value?.hide(),
})


</script>